package com.frejoys.common.jsonserializer;


import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.time.temporal.Temporal;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 自定义序列化修改器
 */
public class CustomBeanSerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        // return super.changeProperties(config, beanDesc, beanProperties);

        // 循环所有的beanPropertyWriter
        for (BeanPropertyWriter writer : beanProperties) {
            if (isArrayType(writer)) {
                // 给writer注册一个自己的nullSerializer
                writer.assignNullSerializer(new CustomNullJsonSerializer.NullArrayJsonSerializer());
                continue;
            }
            if (isStringType(writer)) {
                writer.assignNullSerializer(new CustomNullJsonSerializer.NullStringJsonSerializer());
                continue;
            }
            if (isNumberType(writer)){
                writer.assignNullSerializer(new CustomNullJsonSerializer.NullNumberJsonSerializer());
                continue;
            }
            if (isDateType(writer)){
                writer.assignNullSerializer(new CustomNullJsonSerializer.NullDateJsonSerializer());
                continue;
            }
            if (isBooleanType(writer)){
                writer.assignNullSerializer(new CustomNullJsonSerializer.NullBooleanJsonSerializer());
            }
        }

        return beanProperties;
    }

    /**
     * 是否是数组
     */
    private boolean isArrayType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
    }

    /**
     * 是否是String
     */
    private boolean isStringType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
    }

    /**
     * 是否是数值类型
     */
    private boolean isNumberType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return Number.class.isAssignableFrom(clazz);
    }

    /**
     * 是否是boolean
     */
    private boolean isBooleanType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return clazz.equals(Boolean.class);
    }
    /**
     * 是否是date
     */
    private boolean isDateType(BeanPropertyWriter writer) {
        Class<?> clazz = writer.getType().getRawClass();
        return clazz.equals(Date.class) || Temporal.class.isAssignableFrom(clazz);
    }

}
